﻿namespace Compass.Wpf.Converters;
//给DataGrid添加行号
public class DataGridShowRowIndexBehavior
{
    public static bool GetShowRowIndex(DependencyObject obj)
    {
        return (bool)obj.GetValue(ShowRowIndexProperty);
    }
    [AttachedPropertyBrowsableForType(typeof(DataGrid))]
    public static void SetShowRowIndex(DependencyObject obj, bool value)
    {
        obj.SetValue(ShowRowIndexProperty, value);
    }
    /// <summary>
    /// 设置是否显示行号
    /// </summary>
    public static readonly DependencyProperty ShowRowIndexProperty = DependencyProperty.RegisterAttached("ShowRowIndex", typeof(bool), typeof(DataGridShowRowIndexBehavior), new PropertyMetadata(false, ShowRowIndexPropertyChanged));

    private static void ShowRowIndexPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var dataGrid = d as DataGrid;
        if (dataGrid==null) return;

        dataGrid.LoadingRow += OnInitialized;
    }

    private static void OnInitialized(object? sender, EventArgs e)
    {
        DataGrid dataGrid = sender as DataGrid;
        if (dataGrid == null)
        {
            return;
        }
        foreach (var item in dataGrid.Items)
        {
            var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);
            if (row == null)
            {
                return;
            }
            row.Header = row.GetIndex() + 1;
        }
    }

    private static void OnSourceUpdated(object sender, RoutedEventArgs e)
    {
        DataGrid dataGrid = sender as DataGrid;
        if (dataGrid == null)
        {
            return;
        }
        foreach (var item in dataGrid.Items)
        {
            var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);
            if (row == null)
            {
                return;
            }
            row.Header = row.GetIndex() + 1;
        }

    }
}